package com.SmartCare.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.SmartCare.common.dto.apiLog.ApiLogDTO;
import com.SmartCare.mapper.role.ElderlyInformationMapper;
import com.SmartCare.mapper.role.UserMapper;
import com.SmartCare.mapper.role.UserRelationshipMapper;
import com.SmartCare.pojo.role.ElderlyInformation;
import com.SmartCare.pojo.role.User;
import com.SmartCare.pojo.role.UserRelationship;
import com.SmartCare.pojo.apiLog.ApiLog;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用药途径转化工具
 */

@Service
public class ApiLogsTransToDTO {
    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRelationshipMapper userRelationshipMapper;

    @Resource
    private ElderlyInformationMapper elderlyInformationMapper;

    public List<ApiLogDTO> trans(List<ApiLog> list) {
        //将日志信息转成DTO
        List<ApiLogDTO> result = new ArrayList<>();
        CopyOptions options = CopyOptions.create().setIgnoreProperties("user_id");
        for (ApiLog apiLog : list) {
            ApiLogDTO dto = new ApiLogDTO();
            BeanUtil.copyProperties(apiLog, dto, options);
            //获取用户
            User user = userMapper.selectById(apiLog.getUserId());
            dto.setUser(user);
            result.add(dto);
            //获取老人
            if (user != null) {
                QueryWrapper<UserRelationship> qw = new QueryWrapper<>();
                qw.eq("family_member_id", user.getUserId());
                //获取该用户对应的老人的id数组
                List<UserRelationship> relationships = userRelationshipMapper.selectList(qw);
                List<Long> elderIds = relationships.stream().map(UserRelationship::getElderlyId).collect(Collectors.toList());
                //获取老人列表
                QueryWrapper<ElderlyInformation> eqw = new QueryWrapper<>();
                if (elderIds.isEmpty()) {
                    dto.setElders(new ArrayList<>());
                } else {
                    eqw.in("elderly_id", elderIds);
                    List<ElderlyInformation> elders = elderlyInformationMapper.selectList(eqw);
                    dto.setElders(elders);
                }
            }
        }
        return result;
    }
}
